package ut.servlet.member.paypal;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
public class DoPayment extends HttpServlet{
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("utf-8");
		int money;
		String token, payerId;
		if(request.getParameter("money") == null || request.getParameter("token") == null || request.getParameter("payer_id") == null){
			return;
		}else{
			try{
				money = Integer.parseInt(request.getParameter("money"));
			}catch(NumberFormatException e){
				return;
			}
			token = request.getParameter("token");
			payerId = request.getParameter("payer_id");
		}
		// 確認使用者已經完成信箱驗證
		ut.data.User user = (ut.data.User)request.getSession().getAttribute("user");
		if(user.verify == 0){
			return;
		}
		// 開始進行處理
		String body = null;
		try{
			body = ut.util.HttpClient.sendHttpRequest(System.getProperty("paypal.endpoint"),
				System.getProperty("paypal.auth") + "&METHOD=DoExpressCheckoutPayment&TOKEN=" + java.net.URLEncoder.encode(token, "utf-8") + "&PAYERID=" + payerId + "&PAYMENTACTION=Sale&PAYMENTREQUEST_0_CURRENCYCODE=TWD&PAYMENTREQUEST_0_AMT=" + money + "&PAYMENTREQUEST_0_ITEMAMT=" + money + "&PAYMENTREQUEST_0_PAYMENTACTION=Sale" +
				"&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital&L_PAYMENTREQUEST_0_NAME0=NTD" + money + "&L_PAYMENTREQUEST_0_QTY0=1&L_PAYMENTREQUEST_0_AMT0=" + money, false);
		}catch(java.io.UnsupportedEncodingException e){
			response.setIntHeader("result", -1);
			return;
		}
		if(body.indexOf("ACK=Success") > -1 || body.indexOf("ACK=SuccessWithWarning") > -1){ // 付款成功
			int startIndex = body.indexOf("TRANSACTIONID=") + 14;
			int endIndex = body.indexOf("&", startIndex) > -1 ? body.indexOf("&", startIndex) : body.length();
			String paypalTransactionId = body.substring(startIndex, endIndex);
			if(ut.data.Transaction.deposit(user, money, paypalTransactionId)){ // 資料處理成功
				response.setIntHeader("result", 1);
			}else{ // 資料處理失敗，進行退款
				ut.util.HttpClient.sendHttpRequest(System.getProperty("paypal.endpoint"), System.getProperty("paypal.auth") + "&METHOD=RefundTransaction&TRANSACTIONID=" + paypalTransactionId + "&REFUNDTYPE=Full", false);
				response.setIntHeader("result", 0);
			}
		}else{ // 付款失敗
			response.setIntHeader("result", 0);
		}
	}
}